package com.lagou.session;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import com.lagou.utils.GenericTokenParser;
import com.lagou.utils.ParameterMapping;
import com.lagou.utils.ParameterMappingTokenHandler;

import javax.sql.DataSource;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    private Configuration configuration;

    public SimpleExecutor(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InstantiationException, InvocationTargetException {
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        String sql1 = boundSql.getSql();
        DataSource dataSource = configuration.getDataSource();
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement(sql1);
        String parameterType = mappedStatement.getParameterType();
        Class<?> classType = getClassType(parameterType);
        List<ParameterMapping> list = boundSql.getList();
        for (int i = 0; i < list.size(); i++) {
            ParameterMapping parameterMapping = list.get(i);
            String content = parameterMapping.getContent();
            Field field = classType.getDeclaredField(content);
            field.setAccessible(true);
            Object o = field.get(params[0]);
            preparedStatement.setObject(i + 1, o);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultClass = getClassType(resultType);
        List<Object> arrayList = new ArrayList<>();
        while (resultSet.next()) {
            Object o1 = resultClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object object = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o1, object);

//                Field field = resultClass.getDeclaredField(columnName);
//                field.setAccessible(true);
//                field.set(o1, object);
            }
            arrayList.add(o1);
        }
        return (List<E>) arrayList;
    }


    @Override
    public int nativeSql(MappedStatement mappedStatement, Object... params) throws Exception {
        //首先获取数据库链接
        Connection connection = this.configuration.getDataSource().getConnection();
        //获取sql
        String xmlSql = mappedStatement.getSql();
        //将sql进行转换预编译sql
        BoundSql boundSql = getBoundSql(xmlSql);
        String nativeSql = boundSql.getSql();
        //获取sql执行器
        PreparedStatement preparedStatement = connection.prepareStatement(nativeSql);
        //set参数
        String parameterType = mappedStatement.getParameterType();
        Class<?> classType = getClassType(parameterType);
        List<ParameterMapping> list = boundSql.getList();
        for (int i = 0; i < list.size(); i++) {
            Field declaredField = classType.getDeclaredField(
                    list.get(i).getContent()
            );
            declaredField.setAccessible(true);
            Object parameterValue = declaredField.get(params[0]);
            preparedStatement.setObject(i + 1, parameterValue);
        }
        return preparedStatement.executeUpdate();
    }



    private Class getClassType(String type) throws ClassNotFoundException {
        if (type != null) {
            Class<?> aClass = Class.forName(type);
            return aClass;
        }
        return null;
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser parser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = parser.parse(sql);
        BoundSql boundSql = new BoundSql();
        boundSql.setSql(parse);
        boundSql.setList(parameterMappingTokenHandler.getParameterMappings());
        return boundSql;
    }
}
